<script setup lang="ts">
import { useI18n } from "vue-i18n";
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { loginRules } from "./utils/rule";
import { useNav } from "@/layout/hooks/useNav";
import type { FormInstance } from "element-plus";
import { $t, transformI18n } from "@/plugins/i18n";
import { useLayout } from "@/layout/hooks/useLayout";
import { useUserStoreHook } from "@/store/modules/user";
import { initRouter, getTopMenu } from "@/router/utils";
import { bg, avatar, illustration } from "./utils/static";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ref, reactive, toRaw, onMounted, onBeforeUnmount } from "vue";
import { useTranslationLang } from "@/layout/hooks/useTranslationLang";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";

import dayIcon from "@/assets/svg/day.svg?component";
import darkIcon from "@/assets/svg/dark.svg?component";
import globalization from "@/assets/svg/globalization.svg?component";
import Lock from "@iconify-icons/ri/lock-fill";
import Check from "@iconify-icons/ep/check";
import User from "@iconify-icons/ri/user-3-fill";
import { loginApi } from "@/api/login";
import { setToken } from "@/utils/auth";

defineOptions({
  name: "Login"
});
const router = useRouter();
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();

const { initStorage } = useLayout();
initStorage();

const { t } = useI18n();
const { dataTheme, overallStyle, dataThemeChange } = useDataThemeChange();
dataThemeChange(overallStyle.value);
const { title, getDropdownItemStyle, getDropdownItemClass } = useNav();
const { locale, translationCh, translationEn } = useTranslationLang();

const ruleForm = reactive({
  username: "",
  password: ""
});

const onLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    // if (valid) {
    //   loading.value = true;
    //   useUserStoreHook()
    //     .loginByUsername({ username: ruleForm.username, password: "admin123" })
    //     .then(res => {
    //       if (res.success) {
    //         // 获取后端路由
    //         return initRouter().then(() => {
    //           router.push(getTopMenu(true).path).then(() => {
    //             message(t("login.pureLoginSuccess"), { type: "success" });
    //           });
    //         });
    //       } else {
    //         message(t("login.pureLoginFail"), { type: "error" });
    //       }
    //     })
    //     .finally(() => (loading.value = false));
    // }
    if (valid) {
      loading.value = true;
      console.log("ruleForm:", ruleForm);
      const res = await loginApi(ruleForm);
      console.log("登录结果：", res);
      if (res.code === 200) {
        const userStore = useUserStoreHook();
        const userData = res.data;
        // 存储用户基本信息
        userStore.SET_USERNAME(userData.username);
        userStore.SET_AVATAR(userData.avatar || ""); // 处理 null 值
        // 存储角色信息
        // userStore.SET_ROLES([userData.role.roleKey]); // 将角色 key 转为数组
        // 存储权限信息
        // const permissions = userData.perms.map(perm => perm.perms);
        // userStore.SET_PERMS(permissions);
        // 存储 token
        setToken({
          accessToken: userData.token,
          expires: 1802457801000, // 使用后端返回的过期时间
          refreshToken: userData.token, // 如果没有刷新token，暂时使用相同的token
          username: userData.username,
          nickname: userData.nickname
        });
        // 获取后端路由后直接跳转到welcome页面
        await initRouter();
        await router.push("/welcome");
        message("登录成功", { type: "success" });
      } else {
        message(res.data.message || "登录失败", { type: "error" });
      }
    }
  });
};

/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (["Enter", "NumpadEnter"].includes(code)) {
    onLogin(ruleFormRef.value);
  }
}

onMounted(() => {
  window.document.addEventListener("keypress", onkeypress);
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});
</script>

<template>
  <div class="select-none intangible-heritage-login">
    <div class="heritage-background">
      <!-- 背景装饰元素 -->
      <div class="heritage-pattern top-left" />
      <div class="heritage-pattern top-right" />
      <div class="heritage-pattern bottom-left" />
      <div class="heritage-pattern bottom-right" />
    </div>

    <div class="flex-c absolute right-5 top-3 z-10">
      <!-- 主题 -->
      <el-switch
        v-model="dataTheme"
        inline-prompt
        :active-icon="dayIcon"
        :inactive-icon="darkIcon"
        class="heritage-switch"
        @change="dataThemeChange"
      />
    </div>

    <div class="login-container">
      <div class="heritage-left-panel">
        <div class="heritage-illustration">
          <img
            style="width: 250px; height: 500px"
            src="@/assets/login/c7309535ec9cd1c670da565a6ffd395.png"
            alt=""
          />
        </div>
        <div class="heritage-decoration" />
      </div>

      <div class="login-box heritage-login-box">
        <div class="login-form heritage-form">
          <div class="heritage-logo-container" />

          <Motion>
            <h2 class="heritage-title">华衣甄选-BOSS端</h2>
            <div class="heritage-subtitle">传承非遗文化 · 弘扬汉服之美</div>
          </Motion>

          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="loginRules"
            size="large"
            class="heritage-el-form"
          >
            <Motion :delay="100">
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: transformI18n($t('login.pureUsernameReg')),
                    trigger: 'blur'
                  }
                ]"
                prop="username"
                class="heritage-form-item"
              >
                <el-input
                  v-model="ruleForm.username"
                  clearable
                  :placeholder="t('login.pureUsername')"
                  :prefix-icon="useRenderIcon(User)"
                  class="heritage-input"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="150">
              <el-form-item prop="password" class="heritage-form-item">
                <el-input
                  v-model="ruleForm.password"
                  clearable
                  show-password
                  :placeholder="t('login.purePassword')"
                  :prefix-icon="useRenderIcon(Lock)"
                  class="heritage-input"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="250">
              <el-button
                class="w-full mt-4 heritage-button"
                size="default"
                type="primary"
                :loading="loading"
                @click="onLogin(ruleFormRef)"
              >
                {{ t("login.pureLogin") }}
              </el-button>
            </Motion>
          </el-form>

          <div class="heritage-footer">
            <div class="heritage-seal" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import url("@/style/login.css");

/* 非遗风格登录页样式 */
.intangible-heritage-login {
  position: relative;
  width: 100%;
  height: 100vh;
  overflow: hidden;
  background-color: #f9f1e6; /* 米色背景 */
}

.heritage-background {
  position: absolute;
  width: 100%;
  height: 100%;
  background-image: url("data:image/svg+xml,%3Csvg width='100' height='100' viewBox='0 0 100 100' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M11 18c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm48 25c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm-43-7c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm63 31c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM34 90c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm56-76c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM12 86c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm28-65c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm23-11c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-6 60c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm29 22c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zM32 63c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm57-13c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-9-21c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM60 91c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM35 41c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM12 60c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2z' fill='%23b88d56' fill-opacity='0.1' fill-rule='evenodd'/%3E%3C/svg%3E");
}

.heritage-pattern {
  position: absolute;
  width: 300px;
  height: 300px;
  background-size: contain;
  background-repeat: no-repeat;
  opacity: 0.15;
}

.top-left {
  top: 0;
  left: 0;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='200' height='200' viewBox='0 0 200 200'%3E%3Cpath fill='%23b88d56' d='M0 0h200v200H0z'/%3E%3Cpath fill='%23f9f1e6' d='M200 200H0V0h200v200zM20 20v160h160V20H20z'/%3E%3Cpath fill='%23f9f1e6' d='M40 40v120h120V40H40zm100 100H60V60h80v80z'/%3E%3Cpath fill='%23f9f1e6' d='M80 80v40h40V80H80z'/%3E%3C/svg%3E");
}

.top-right {
  top: 0;
  right: 0;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='200' height='200' viewBox='0 0 200 200'%3E%3Cpath fill='none' stroke='%23b88d56' stroke-width='2' d='M0 0h200v200H0z'/%3E%3Ccircle cx='100' cy='100' r='80' fill='none' stroke='%23b88d56' stroke-width='2'/%3E%3Ccircle cx='100' cy='100' r='60' fill='none' stroke='%23b88d56' stroke-width='2'/%3E%3Ccircle cx='100' cy='100' r='40' fill='none' stroke='%23b88d56' stroke-width='2'/%3E%3Ccircle cx='100' cy='100' r='20' fill='none' stroke='%23b88d56' stroke-width='2'/%3E%3C/svg%3E");
}

.bottom-left {
  bottom: 0;
  left: 0;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='200' height='200' viewBox='0 0 200 200'%3E%3Cpath fill='none' stroke='%23b88d56' stroke-width='2' d='M20 20h160v160H20z'/%3E%3Cpath fill='none' stroke='%23b88d56' stroke-width='2' d='M0 0l200 200M200 0L0 200'/%3E%3Cpath fill='none' stroke='%23b88d56' stroke-width='2' d='M100 0v200M0 100h200'/%3E%3C/svg%3E");
}

.bottom-right {
  bottom: 0;
  right: 0;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='200' height='200' viewBox='0 0 200 200'%3E%3Cpath fill='none' stroke='%23b88d56' stroke-width='2' d='M100 0C44.8 0 0 44.8 0 100s44.8 100 100 100 100-44.8 100-100S155.2 0 100 0zm0 180c-44.2 0-80-35.8-80-80s35.8-80 80-80 80 35.8 80 80-35.8 80-80 80z'/%3E%3Cpath fill='none' stroke='%23b88d56' stroke-width='2' d='M100 140c-22.1 0-40-17.9-40-40s17.9-40 40-40 40 17.9 40 40-17.9 40-40 40z'/%3E%3C/svg%3E");
}

.login-container {
  position: relative;
  display: flex;
  width: 80%;
  max-width: 1200px;
  height: 600px;
  margin: 0 auto;
  top: 50%;
  transform: translateY(-50%);
  box-shadow: 0 8px 30px rgba(184, 141, 86, 0.2);
  border-radius: 12px;
  overflow: hidden;
  z-index: 1;
}

.heritage-left-panel {
  flex: 1;
  background: linear-gradient(135deg, #b88d56, #8c5e2a);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
}

.heritage-illustration {
  width: 80%;
  height: 80%;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.heritage-illustration::before {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100' height='100' viewBox='0 0 100 100'%3E%3Cpath fill='%23ffffff' fill-opacity='0.1' d='M20 20h60v60H20z'/%3E%3Cpath fill='none' stroke='%23ffffff' stroke-opacity='0.2' stroke-width='1' d='M0 0l100 100M100 0L0 100'/%3E%3C/svg%3E");
  opacity: 0.3;
}

.heritage-login-box {
  flex: 1;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.heritage-form {
  width: 80%;
  max-width: 400px;
  padding: 40px 0;
  position: relative;
}

.heritage-logo-container {
  text-align: center;
  margin-bottom: 20px;
}

.heritage-avatar {
  width: 100px;
  height: 100px;
  border: 4px solid rgba(184, 141, 86, 0.2);
  border-radius: 50%;
  padding: 4px;
}

.heritage-title {
  font-size: 28px;
  color: #8c5e2a;
  text-align: center;
  margin-bottom: 8px;
  font-weight: 600;
  letter-spacing: 1px;
}

.heritage-subtitle {
  font-size: 14px;
  color: #b88d56;
  text-align: center;
  margin-bottom: 30px;
  letter-spacing: 2px;
}

.heritage-el-form {
  margin-top: 20px;
}

.heritage-form-item {
  margin-bottom: 25px;
}

.heritage-input :deep(.el-input__wrapper) {
  background-color: rgba(249, 241, 230, 0.5);
  border: 1px solid rgba(184, 141, 86, 0.3);
  border-radius: 8px;
  box-shadow: none;
  transition: all 0.3s;
}

.heritage-input :deep(.el-input__wrapper:hover) {
  border-color: rgba(184, 141, 86, 0.6);
}

.heritage-input :deep(.el-input__wrapper.is-focus) {
  border-color: #b88d56;
  box-shadow: 0 0 0 1px rgba(184, 141, 86, 0.2);
}

.heritage-input :deep(.el-input__prefix-inner) {
  color: #b88d56;
}

.heritage-button {
  height: 46px;
  background: linear-gradient(135deg, #b88d56, #8c5e2a);
  border: none;
  border-radius: 8px;
  font-size: 16px;
  letter-spacing: 2px;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
}

.heritage-button:hover {
  background: linear-gradient(135deg, #c99d66, #9d6f3b);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(184, 141, 86, 0.3);
}

.heritage-button:active {
  transform: translateY(0);
}

.heritage-footer {
  margin-top: 30px;
  text-align: center;
  position: relative;
}

.heritage-seal {
  width: 60px;
  height: 60px;
  margin: 0 auto;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Ccircle cx='50' cy='50' r='45' fill='%23f9f1e6' stroke='%23b88d56' stroke-width='2'/%3E%3Cpath fill='%23b88d56' d='M30 30h40v40H30z'/%3E%3Cpath fill='%23f9f1e6' d='M35 35h30v30H35z'/%3E%3Cpath fill='%23b88d56' d='M45 45h10v10H45z'/%3E%3C/svg%3E");
  background-size: contain;
  opacity: 0.6;
}

.heritage-decoration {
  position: absolute;
  width: 100%;
  height: 100%;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100' height='100' viewBox='0 0 100 100'%3E%3Cpath fill='none' stroke='%23ffffff' stroke-opacity='0.2' stroke-width='1' d='M10 10h80v80H10z'/%3E%3C/svg%3E");
  opacity: 0.3;
}

.heritage-switch :deep(.el-switch__core) {
  background-color: rgba(184, 141, 86, 0.3);
  border-color: rgba(184, 141, 86, 0.5);
}

.heritage-switch :deep(.el-switch__core .el-switch__action) {
  background-color: #f9f1e6;
}

.heritage-switch.is-checked :deep(.el-switch__core) {
  background-color: #b88d56;
  border-color: #8c5e2a;
}

@media (max-width: 992px) {
  .login-container {
    width: 90%;
    height: auto;
    flex-direction: column;
  }

  .heritage-left-panel {
    display: none;
  }

  .heritage-login-box {
    width: 100%;
    padding: 40px 0;
  }
}
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}

.translation {
  ::v-deep(.el-dropdown-menu__item) {
    padding: 5px 40px;
  }

  .check-zh {
    position: absolute;
    left: 20px;
  }

  .check-en {
    position: absolute;
    left: 20px;
  }
}
</style>
